package czk.concrent.synControl;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/6/2 21:00
 */

/**
 * 同步打印
 */
public class Test {
    public static void main(String[] args) {
        WaitAndNotify waitAndNotify=new WaitAndNotify(1,5);
        new Thread(()->{
            waitAndNotify.print("a",1,2);
        }).start();
        new Thread(()->{
            waitAndNotify.print("b",2,3);
        }).start();
        new Thread(()->{
            waitAndNotify.print("c",3,1);
        }).start();
    }
}
class WaitAndNotify{
    // 等代标记
    private int i;
    // 循环次数
    private int loopNumber;

    public WaitAndNotify(int i, int loopNumber) {
        this.i = i;
        this.loopNumber = loopNumber;
    }

    /**
     *
     * @param content 打印内容
     * @param waitFlag 等代标记
     * @param nextFlag 下一标记
     */
    public void print(String content,int waitFlag,int nextFlag){
        for (int j = 0; j <loopNumber ; j++) {
            synchronized (this){
                while (i!=waitFlag){
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.print(content);
                i=nextFlag;
                this.notifyAll();
            }
        }
    }
}
